<template>
  <a-form
    ref="formRef"
    :model="formState"
    layout="vertical"
    name="deviceForm"
  >
    <a-row :gutter="24">
      <!-- 第一行 -->
      <a-col :span="12">
        <a-form-item label="设备名称" name="name" :rules="[{ required: true, message: '请输入设备名称' }]">
          <a-input v-model:value="formState.name" placeholder="例如：A座大厅入口监控" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="设备唯一ID (deviceId)" name="deviceUid" :rules="[{ required: true, message: '请输入设备唯一ID' }]">
          <a-input v-model:value="formState.deviceUid" placeholder="通常由硬件MAC地址生成" />
        </a-form-item>
      </a-col>

      <!-- 第二行 -->
      <a-col :span="12">
        <a-form-item label="序列号 (SN)" name="sn">
          <a-input v-model:value="formState.sn" placeholder="请从设备标签上查找" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="设备型号" name="model">
          <a-input v-model:value="formState.model" placeholder="例如：XC-IVS8008-1U" />
        </a-form-item>
      </a-col>

      <!-- 第三行 -->
      <a-col :span="12">
        <a-form-item label="安装位置" name="locationId" :rules="[{ required: true, message: '请选择安装位置' }]">
          <a-tree-select
            v-model:value="formState.locationId"
            :tree-data="locationTree"
            tree-default-expand-all
            placeholder="请选择"
            :field-names="{ children: 'children', label: 'name', value: 'id' }"
          />
        </a-form-item>
      </a-col>
       <a-col :span="12">
        <a-form-item label="维护责任人" name="maintainer">
          <a-input v-model:value="formState.maintainer" placeholder="请输入维护人员姓名" />
        </a-form-item>
      </a-col>

      <!-- 第四行 -->
      <a-col :span="12">
        <a-form-item label="IP 地址" name="ipAddress" :rules="[{ required: true, message: '请输入IP地址' }]">
          <a-input v-model:value="formState.ipAddress" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="端口" name="port" :rules="[{ required: true, message: '请输入端口' }]">
          <a-input-number v-model:value="formState.port" style="width: 100%" />
        </a-form-item>
      </a-col>
      
      <!-- 第五行 -->
       <a-col :span="12">
        <a-form-item label="设备登录用户名" name="username">
          <a-input v-model:value="formState.username" placeholder="默认为 admin" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="设备登录密码" name="password">
          <a-input-password v-model:value="formState.password" placeholder="请输入设备登录密码" />
        </a-form-item>
      </a-col>
      
      <!-- 第六行 -->
      <a-col :span="12">
        <a-form-item label="出厂日期" name="productionDate">
          <a-date-picker v-model:value="formState.productionDate" style="width: 100%" placeholder="请选择日期" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="安装日期" name="installDate">
          <a-date-picker v-model:value="formState.installDate" style="width: 100%" placeholder="请选择日期" />
        </a-form-item>
      </a-col>

      <!-- 第七行 -->
      <a-col :span="24">
        <a-form-item label="设备描述" name="description">
          <a-textarea v-model:value="formState.description" :rows="3" placeholder="记录设备用途、注意事项等信息" />
        </a-form-item>
      </a-col>

      <!-- 第八行：照片上传 -->
      <a-col :span="24">
        <a-form-item label="设备照片" name="photos">
          <a-spin :spinning="loadingPhotos">
            <a-upload
              v-model:file-list="fileList"
              :action="uploadUrl"
              :headers="uploadHeaders"
              list-type="picture-card"
              @preview="handlePreview"
              @change="handleChange"
            >
              <div v-if="fileList.length < 5">
                <PlusOutlined />
                <div style="margin-top: 8px">上传照片</div>
              </div>
            </a-upload>
          </a-spin>
          <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
            <img alt="预览" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { getLocationTree } from '@/api/locations';
import { getProtectedImage } from '@/api/files';
import { PlusOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';

const props = defineProps({
  initialValues: { type: Object, default: () => ({}) }
});

const formRef = ref();
const formState = ref({});
const locationTree = ref([]);

// --- 照片上传逻辑 ---
const BACKEND_URL = 'http://localhost:9999/api';
const uploadUrl = `${BACKEND_URL}/files/upload`;
const uploadHeaders = { Authorization: `Bearer ${localStorage.getItem('token')}` };

const fileList = ref([]);
const loadingPhotos = ref(false); // 【修正】定义 loadingPhotos 状态
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

const handleCancel = () => {
  previewVisible.value = false;
};

const handlePreview = async (file) => {
  if (!file.url && !file.preview) {
    // 对于刚上传成功、尚未生成 blob url 的文件
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

const handleChange = ({ file, fileList: newFileList }) => {
  if (file.status === 'done') {
    message.success(`${file.name} 上传成功`);
    const responseUrl = file.response?.url;
    if (responseUrl) {
      const uploadedFile = newFileList.find(f => f.uid === file.uid);
      if (uploadedFile) {
        // 【修正】新上传的文件也需要获取受保护的 blob url 来预览
        // 但这里我们先保存相对路径，然后在提交时统一处理
        uploadedFile.relativeUrl = responseUrl; // 保存后端返回的相对路径
        // 为了能立即预览，我们可以临时生成一个 base64 url
        getBase64(uploadedFile.originFileObj).then(base64Url => {
             uploadedFile.url = base64Url;
        });
      }
    }
  } else if (file.status === 'error') {
    message.error(`${file.name} 上传失败`);
  }
  fileList.value = newFileList;
};

const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};

// --- 表单核心逻辑 ---
const fetchLocations = async () => {
  try {
    const response = await getLocationTree();
    locationTree.value = response.data;
  } catch (error) { console.error("Failed to load locations", error); }
};

// 【核心改造】使用一个更健壮的 watch 逻辑
watch(() => props.initialValues, (newVal) => {
  if (!newVal || Object.keys(newVal).length === 0) {
    // 处理新增情况，重置表单
    formState.value = {};
    fileList.value = [];
    return;
  }

  // 处理编辑情况，填充表单
  formState.value = {
    ...newVal,
    // 【重要】后端返回的 locationName 只是用于展示的，表单绑定的是 locationId
    // 我们需要从完整的设备信息中获取 locationId
    locationId: newVal.location?.id || null, 
    productionDate: newVal.productionDate ? dayjs(newVal.productionDate) : null,
    installDate: newVal.installDate ? dayjs(newVal.installDate) : null,
  };
  
  // 异步加载图片
  if (newVal.photos && Array.isArray(newVal.photos)) {
    loadingPhotos.value = true;
    const photoPromises = newVal.photos.map(async (relativeUrl, index) => {
      try {
        const blobUrl = await getProtectedImage(relativeUrl);
        if (blobUrl) {
          return {
            uid: `-photo-${index}-${Date.now()}`,
            name: `photo_${index + 1}.png`,
            status: 'done',
            url: blobUrl,
            relativeUrl: relativeUrl,
          };
        }
      } catch (e) { return null; }
    });
    
    Promise.all(photoPromises).then(results => {
      fileList.value = results.filter(Boolean); // 过滤掉加载失败的图片
      loadingPhotos.value = false;
    });
  } else {
    fileList.value = [];
  }
}, { immediate: true, deep: true });

onMounted(() => {
  fetchLocations();
});

defineExpose({
  validate: async () => {
    try {
      await formRef.value.validate();
      return {
        ...formState.value,
        productionDate: formState.value.productionDate?.format('YYYY-MM-DD'),
        installDate: formState.value.installDate?.format('YYYY-MM-DD'),
        // 【修正】统一从 relativeUrl 或 response.url 提取相对路径
        photos: fileList.value
          .filter(f => f.status === 'done')
          .map(f => f.relativeUrl || f.response?.url),
      };
    } catch (error) {
      console.log('Form validation failed:', error);
      return null;
    }
  }
});
</script>